<template>
  <CardHead title="个人表现趋势" :filters="filters" @on-select="onSelect">
    <div class="w-full rounded-lg px-3">
      <!-- 折线图 -->
      <div class="bg-white rounded-lg">
        <div class="flex items-center justify-start pt-3 pl-3">
          <div class="flex items-center gap-2">
            <p class="text-[#595959] text-sm" @click="showChoosePeople = true">
              {{ selectName }}
            </p>
            <van-icon name="arrow-down" />
          </div>
        </div>
        <template v-if="lineChartData.datas?.length > 0">
          <LineChart :data="lineChartData" />
        </template>
        <template v-else>
          <div class="p-3">
            <ChartEmpty />
          </div>
        </template>
      </div>
    </div>

    <div class="w-full px-3">
      <!--           AI分析 -->
      <div class="bg-white rounded-lg">
        <div
          class="flex items-center justify-between mb-2 bg-gradient-to-r from-[#FFF6FF] to-[#F0F8FF] h-[48px] px-3"
        >
          <div class="flex items-center gap-2">
            <img src="@/icons/svg/myXmate/ai_analysis.svg" alt="AI" class="w-5 h-5" />
            <span
              class="font-bold bg-gradient-to-r from-[#6D1BFF] to-[#1D65FF] bg-clip-text text-transparent"
              >AI分析</span
            >
          </div>

          <div
            class="flex items-center cursor-pointer text-sm"
            @click="showAIData = !showAIData"
          >
            {{ showAIData ? "收起" : "展开" }}
            <van-icon :name="showAIData ? 'arrow-up' : 'arrow-down'"></van-icon>
          </div>
        </div>
        <template v-if="showAIData">
          <CardLoading v-if="aiLoading" />
          <template v-else>
            <div
              v-if="Object.keys(aiData || {}).length > 0"
              class="w-full bg-white rounded-lg px-4 pb-4"
            >
              <div
                v-ai-tip="'bottom-left'"
                class="bg-white rounded-lg mt-4 text-[#262626]"
              >
                <div class="mb-3 mt-3">
                  <div class="flex items-center gap-1 mb-3">
                    <img
                      src="@/icons/svg/myXmate/ai_comment.svg"
                      alt="AI"
                      class="w-5 h-5"
                    />
                    <span class="font-semibold">整体评价</span>
                  </div>
                  <div class="text-[#666] text-sm">
                    <MarkDown :content="aiData.advice" />
                  </div>
                </div>

                <van-divider />

                <div>
                  <div class="flex items-center gap-1 mb-3">
                    <img
                      src="@/icons/svg/myXmate/ai_suggestion.svg"
                      alt="AI"
                      class="w-5 h-5"
                    />

                    <span class="font-semibold">改进建议</span>
                  </div>
                  <div class="text-[#666] text-sm">
                    <MarkDown :content="aiData.advice" />
                  </div>
                </div>
              </div>
            </div>
            <ChartEmpty v-else />
          </template>
        </template>
      </div>
    </div>

    <van-action-sheet
      v-model:show="showChoosePeople"
      :lock-scroll="false"
      title="销售筛选"
    >
      <div class="h-[680px]">
        <choosePeopleView
          @confirm="onConfirmPeople"
          :max-num="1"
          v-if="showChoosePeople"
          :enableCache="true"
          :default-team-id="currentDeptId"
          :default-selected-items="[selectUserObj]"
        />
      </div>
    </van-action-sheet>
  </CardHead>
</template>

<script setup lang="ts">
import CardHead from "@/views/myXmate/myTeam/components/cardHead.vue";
import { computed, onMounted, Ref, ref, watch } from "vue";
import LineChart from "@/components/charts/lineChart.vue";
import { useMyXmateStore } from "@/store";
import { getUserInfo } from "@/utils/auth";
import choosePeopleView from "@/components/choosePeople/choosePeopleView.vue";
import CardLoading from "@/views/myXmate/myTeam/components/cardLoading.vue";

import {
  getUserPerformanceTrendAnalysisAPI,
  getUserTrendsAPI,
  ReportType,
  TargetType,
  ReportDataType,
} from "@/services/myXmate";
import ChartEmpty from "@/components/charts/chartEmpty.vue";
import MarkDown from "@/components/markdown.vue";

import reportOptions from "../reportOptions.json";
import { formatCompletionTime, ParameterDateType } from "@/utils/timeTool";

// 销售表现
const currentFilter: Ref<FilterOptions> = ref(reportOptions[0]);
const filters = [
  {
    text: currentFilter.value?.text,
    type: currentFilter.value?.value,
    options: reportOptions,
  },
];
const lineChartData = ref({});
const aiData = ref(null);
const showAIData = ref(false);
const showChoosePeople = ref(false);
const loading = ref(false);
const aiLoading = ref(false);
const currentDeptId = computed(() => store.noticeBoardPublicParam.currentDept?.id);
const reportType = computed(() => store.noticeBoardPublicParam.reportType);
const startTime = computed(() => store.noticeBoardPublicParam.startDate);
const endTime = computed(() => store.noticeBoardPublicParam.endDate);
const candidateList = computed(() => store.noticeBoardPublicParam.candidateList);
const store = useMyXmateStore();
const selectUserObj = ref(null);

onMounted(() => {
  init();
});

const selectName = computed(() => {
  return selectUserObj.value?.name || selectUserObj.value?.fullname || "请选择销售";
});

const makeParam = () => {
  if (!selectUserObj.value) {
    selectUserObj.value = store.noticeBoardPublicParam.candidateList[0];
  }
  console.log("makeParam beh:", selectUserObj.value);
  const userId = selectUserObj.value?.id;

  let param = {
    orgId: getUserInfo().orgId,
    deptId: currentDeptId.value,
    userId: userId,
    dataType: currentFilter.value?.value as TargetType,
    params: {
      startTime: formatCompletionTime(startTime.value, ParameterDateType.START_DATE),
      endTime: formatCompletionTime(endTime.value, ParameterDateType.ENE_DATE),
      reportType: reportType.value as ReportType,
    },
  };
  console.log("makeParam: ", param);
  return param;
};

const makeAIParam = (trendData: any) => {
  const userName = selectUserObj.value?.username;
  return {
    userName,
    dimension:
      currentFilter.value?.value === ReportDataType.ABILITY ? "能力评估" : "任务达成",
    trendData,
  };
};

// 选中替换表类型
const onSelect = (filterItem) => {
  const { options } = filterItem;
  currentFilter.value = options?.find(
    (temp: FilterOptions) => temp.value === filterItem.value
  );
};
const onConfirmPeople = (op = []) => {
  const arr = op[0] || {};
  selectUserObj.value = arr;
  showChoosePeople.value = false;
  console.log("onConfirmPeople: ", selectUserObj.value);
  init();
};
const init = async () => {
  loading.value = true;
  aiLoading.value = true;
  const param = makeParam();
  const trendData = await getUserTrendsAPI(param);
  lineChartData.value = trendData || {};
  loading.value = false;

  // aiLoading.value = true;
  const aiParam = makeAIParam(trendData);
  console.log("个人趋势 aiParam： ", aiParam);
  aiData.value = await getUserPerformanceTrendAnalysisAPI(aiParam);
  aiLoading.value = false;
  console.log("个人趋势： ", aiData);
};

watch(
  () => [currentDeptId.value, reportType.value, currentFilter.value],
  () => {
    console.log("watch 个人趋势变化");
    init();
  }
);

watch(
  () => [candidateList.value],
  () => {
    console.log("watch 候选人变化");
    selectUserObj.value = store.noticeBoardPublicParam.candidateList[0];
    init();
  }
);
</script>

<style scoped></style>
